const {
    ipcRenderer
} = require('electron');
const EventEmitter = require('events');
const peer = new EventEmitter();

const {desktopCapturer} = window.require('electron');

const video =  document.getElementById('screen-video');

function play(stream) {
    video.srcObject =  stream;
    video.onloadedmetadata = () => {
        video.play();
    }
}

function getScreenStream() {
    return new Promise((resolve, reject) => {
        desktopCapturer.getSources({
            types: ['screen']
        }).then(async sources => {
            console.log('source', sources);
            for (let source of sources) {
                try {
                    const stream = await navigator.mediaDevices.getUserMedia({
                        audio: false,
                        video: {
                            mandatory: {
                                chromeMediaSource: 'desktop',
                                chromeMediaSourceId: source.id,
                                maxHeight: 400,
                                maxHeight: 400
                            }
                        }
                    });
                    play(stream);
                }
                catch (e) {
                    console.error('navigator.mediaDevices.getUserMedia', e);
                }
            }
        });
    });
}

getScreenStream();
//.....
// getScreenStream()

window.onkeydown = function (e) {
    var data = {
        keyCode: e.keyCode,
        shift: e.shiftKey,
        meta: e.metaKey,
        control: e.controlKey,
        alt: e.altKey
    }
    peer.emit('robot', 'key', data) //返回一个键盘类型的事件的结果
}

window.onmouseup = function (e) {
    var data = {
        clientX: e.clientX,
        clientY: e.clientY,
        video: {
            width: video.getBoundingClientRect().width,
            height: video.getBoundingClientRect().height

        }
    }
    peer.emit('robot', 'mouse', data) ////返回一个鼠标类型的事件的结果
}

peer.on('robot', (type, data) => {
    if (type === 'mouse') {
        data.screen = {
            width: window.screen.width,
            height: window.screen.height
        }
    }
    setTimeout(() => {
        ipcRenderer.send('robot', type, data) //********通信**渲染进程
    }, 1000);
})